package middlewares

import (
	"github.com/gin-gonic/gin"
	"pharymacy-management-system/network"
	"pharymacy-management-system/pkg/jwt"
	"strings"
)

// JWTAuthMiddleware jwt认证中间件
func JWTAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		// 获取authorization header
		tokenString := c.GetHeader("Authorization")
		// validate token format
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			network.ResponseError(c, network.CodeNeedAuth)
			c.Abort()
			return
		}
		// 按空格分割
		parts := strings.SplitN(tokenString, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			network.ResponseError(c, network.CodeInvalidAuth)
			c.Abort()
			return
		}

		// parts[1]是获取到的tokenString，我们使用之前定义好的解析JWT的函数来解析它
		mc, err := jwt.ParseToken(parts[1])
		if err != nil {
			network.ResponseError(c, network.CodeInvalidAuth)
			c.Abort()
			return
		}
		// 将获取到的信息写入上下文
		c.Set(network.CtxUserIDKey, mc.UserID)
		c.Next()
	}
}
